﻿using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PVReportDeployer
{
    /// <summary>
    /// Interaction logic for ChooseSharePointSource.xaml
    /// </summary>
    public partial class DownloadPVWindow : Window
    {
        private ObservableCollection<string> leftCollection;
        private ObservableCollection<string> rightCollection;
        private string tmpDownloadFolder;
        public DownloadPVWindow()
        {
            InitializeComponent();
            this.tmpDownloadFolder = System.IO.Path.GetTempPath() + "PVReportDownload" + System.IO.Path.DirectorySeparatorChar;
            this.leftCollection = new ObservableCollection<string>();
            this.rightCollection = new ObservableCollection<string>();
            this.leftList.ItemsSource = leftCollection;
            this.rightList.ItemsSource = rightCollection;
        }

        
        /// <summary>
        /// Item to right.
        /// </summary>
        private void toRight_Click(object sender, RoutedEventArgs e)
        {
            var items = this.leftList.SelectedItems;
            var itemList = new List<string>();
            foreach (var item in items)
            {
                itemList.Add(item as string);
            }
            foreach (var item in itemList)
            {
                this.rightCollection.Add(item);
                this.leftCollection.Remove(item);
            }
        }
        /// <summary>
        /// Item to left.
        /// </summary>
        private void toLeft_Click(object sender, RoutedEventArgs e)
        {
            var items = this.rightList.SelectedItems;
            var itemList = new List<string>();
            foreach (var item in items)
            {
                itemList.Add(item as string);
            }
            foreach (var item in itemList)
            {
                this.rightCollection.Remove(item);
                this.leftCollection.Add(item);
            }
        }
        /// <summary>
        /// Load file names from SharePoint
        /// </summary>
        private void LoadBtn_Click(object sender, RoutedEventArgs e)
        {
            this.leftCollection.Clear();
            this.rightCollection.Clear();
            try
            {
                using (ClientContext client = new ClientContext(this.baseURL.Text))
                {
                    SecureString password = new SecureString();
                    client.Credentials = new NetworkCredential(this.userTB.Text, this.psdTB.SecurePassword, this.domainTB.Text);
                    string reportsLoc = this.baseURL.Text + "/" + this.foldRelativeURL.Text;
                    Web web = client.Web;
                    Folder folder = web.GetFolderByServerRelativeUrl(reportsLoc);

                    client.Load(folder);
                    client.Load(folder.Files);
                    client.ExecuteQuery();
                    foreach (var file in folder.Files)
                    {
                        // We have all the list item data. For example, Title. 
                        this.leftCollection.Add(file.Name);
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error Occured");
            }
        }
        /// <summary>
        /// Download button clicked.
        /// </summary>
        private void DownloadBtn_Click(object sender, RoutedEventArgs e)
        {
            // clear tmp folder
            if (Directory.Exists(this.tmpDownloadFolder))
            {
                System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(this.tmpDownloadFolder);
                foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
                foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);

            }
            else
            {
                Directory.CreateDirectory(tmpDownloadFolder);
            }

            foreach (var item in this.rightCollection)
            {
                downloadPVReport(item);
            }

            // close  windows
            this.DialogResult = true;
            this.Close();
        }

        /// <summary>
        /// Download power view report to tmpDownloadFolder.
        /// </summary>
        /// <param name="fileName">report name</param>
        private void downloadPVReport(string fileName)
        {
            // do download
            try
            {
                using (ClientContext client = new ClientContext(this.baseURL.Text))
                {
                    SecureString password = new SecureString();
                    client.Credentials = new NetworkCredential(this.userTB.Text, this.psdTB.SecurePassword, this.domainTB.Text);
                    string reportSrc = this.baseURL.Text + "/" + this.foldRelativeURL.Text + "/" + fileName;
                    string reportDst = this.tmpDownloadFolder + fileName;
                    Uri srcUri = new Uri(this.baseURL.Text + "/" + this.foldRelativeURL.Text + "/" + fileName);

                    using (FileInformation ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(client, srcUri.AbsolutePath))
                    {
                        using (Stream destFile = System.IO.File.OpenWrite(reportDst))
                        {
                            byte[] buffer = new byte[8 * 1024];
                            int len;
                            while ((len = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                destFile.Write(buffer, 0, len);
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Download " + fileName + " Failed !");
            }
        }


    }
}
